package cn.edu.lcu.cs.javaprogramming.gui;

import cn.edu.lcu.cs.javaprogramming.annotations.JTableColumnProcessor;
import cn.edu.lcu.cs.javaprogramming.collection.Score;
import cn.edu.lcu.cs.javaprogramming.collection.ScoreUtil;

import javax.swing.*;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableModel;
import java.awt.event.*;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

public class ScoreList extends JDialog {
    /**
     * 成绩集合
     */
    private Collection<Score> scores = ScoreUtil.getScores();
    private JPanel contentPane;
    private JButton buttonSearch;
    private JButton buttonExit;
    private JTextField searchField;
    private JTable scoreTable;

    public ScoreList() {
        setContentPane(contentPane);
        setModal(true);
        getRootPane().setDefaultButton(buttonSearch);


        buttonExit.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                onCancel();
            }
        });

        // 点击 X 时调用 onCancel()
        setDefaultCloseOperation(DISPOSE_ON_CLOSE);
        addWindowListener(new WindowAdapter() {
            public void windowClosing(WindowEvent e) {
                onCancel();
            }
        });

        // 遇到 ESCAPE 时调用 onCancel()
        contentPane.registerKeyboardAction(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                onCancel();
            }
        }, KeyStroke.getKeyStroke(KeyEvent.VK_ESCAPE, 0), JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT);
        buttonExit.addActionListener((e) -> dispose());
        buttonSearch.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                // 获取用户输入的查询关键词
                String searchKey = searchField.getText();
                Collection<Score> searchedScores = scores;
                // 根据查询关键词，查询符合条件的成绩
                if (searchKey != null && !searchKey.trim().isEmpty()) {
                    searchedScores = scores.stream()
                            .filter(score -> (score.getStudentNo() + "\t" + score.getStudentName()).contains(searchKey))
                            .toList();
                }

                Object[][] rows = JTableColumnProcessor.getRows(searchedScores);
                Object[] columnNames = JTableColumnProcessor.getColumnNames(Score.class);
                DefaultTableModel tableModel = new DefaultTableModel(rows, columnNames);
                // 一旦设置了模型数据，表格的显示就会更新。
                scoreTable.setModel(tableModel);
            }
        });
    }

    private void onCancel() {
        // 必要时在此处添加您的代码
        dispose();
    }

    public static void main(String[] args) {
        ScoreList dialog = new ScoreList();
        dialog.pack();
        dialog.setVisible(true);
        System.exit(0);
    }
}
